﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace popoBCadd_in
{
    class CBC
    {
        static int jumlahblock;
        static byte[][] messageblock;
        static int blocksize;

        private static void createblocks(byte[] message)
        {
            jumlahblock = (message.Length / blocksize);
            messageblock = new byte[jumlahblock][];
            int messagecounter = 0;

            for (int i = 0; i < jumlahblock; i++)
            {
                messageblock[i] = new byte[blocksize];
                for (int j = 0; j < blocksize; j++)
                {
                    messageblock[i][j] = message[messagecounter];
                    messagecounter++;
                }
            }
        }

        public static byte[] encrypt(byte[] message, byte[] key, byte[] iv)
        {
            blocksize = key.Length;
            createblocks(message);
            byte[] hasil = new byte[message.Length];
            int ihasil = 0;
            byte[] Csebelumnya = iv;
            byte[] hasilsementara;

            for (int i = 0; i < jumlahblock; i++)
            {
                hasilsementara = generateTrueKey.XorNBitKey(Csebelumnya,messageblock[i],blocksize);
                Csebelumnya = feistel.feistelencrypt(hasilsementara, key);
                for (int j = 0; j < blocksize; j++)
                {
                    hasil[ihasil++] = Csebelumnya[j];
                }
            }

            return hasil;
        }

        public static byte[] decrypt(byte[] message, byte[] key, byte[] iv)
        {
            blocksize = key.Length;
            createblocks(message);
            byte[] hasil = new byte[message.Length];
            int ihasil = 0;
            byte[] hasilsementara;

            hasilsementara = feistel.feisteldecrypt(messageblock[0], key);
            hasilsementara = generateTrueKey.XorNBitKey(hasilsementara, iv, blocksize);
            for (int j = 0; j < blocksize; j++)
            {
                hasil[ihasil++] = hasilsementara[j];
            }

            for (int i = 1; i < jumlahblock; i++)
            {
                hasilsementara = feistel.feisteldecrypt(messageblock[0], key);
                hasilsementara = generateTrueKey.XorNBitKey(hasilsementara, messageblock[i-1], blocksize);
                for (int j = 0; j < blocksize; j++)
                {
                    hasil[ihasil++] = hasilsementara[j];
                }
            }

            return hasil;
        }
    }
}
